import os
import magic
from werkzeug.utils import secure_filename
from flask import current_app


def validate_file(file_stream):
    """深度验证文件类型"""
    allowed = current_app.config['ALLOWED_EXTENSIONS']
    filename = secure_filename(file_stream.filename)

    # 基础验证
    if '.' not in filename:
        raise ValueError('无效的文件类型')
    ext = filename.rsplit('.', 1)[1].lower()
    if ext not in allowed:
        raise ValueError('不允许的文件扩展名')

    # 使用magic进行内容验证
    file_stream.seek(0)
    mime = magic.from_buffer(file_stream.read(1024), mime=True)
    valid_mimes = {
        'txt': 'text/plain',
        'pdf': 'application/pdf',
        'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
    }
    if mime != valid_mimes.get(ext):
        raise ValueError('文件内容类型不匹配')

    return filename


def process_uploaded_file(file):
    try:
        filename = validate_file(file)
        filepath = os.path.join(
            current_app.config['UPLOAD_FOLDER'],
            filename
        )
        file.save(filepath)

        # 读取文件内容（示例仅处理txt）
        with open(filepath, 'r', encoding='utf-8') as f:
            content = f.read()

        os.remove(filepath)
        return content
    except Exception as e:
        current_app.logger.error(f"文件处理失败: {str(e)}")
        raise